import React, { useState } from 'react';
import { Plus, Edit2, Trash2, Save, X, Eye, EyeOff } from 'lucide-react';
import { DiaryTemplate, TemplateSection, TemplateCategory, TEMPLATE_CATEGORIES } from '../types/templates';
import { useDiaryStore } from '../store/diaryStore';

interface TemplateManagerProps {
  onClose: () => void;
}

const TemplateManager: React.FC<TemplateManagerProps> = ({ onClose }) => {
  const { customTemplates, addCustomTemplate, updateTemplate, deleteTemplate } = useDiaryStore();
  const [editingTemplate, setEditingTemplate] = useState<DiaryTemplate | null>(null);
  const [isCreating, setIsCreating] = useState(false);
  const [formData, setFormData] = useState<Partial<DiaryTemplate> & { estimatedTime: number }>({
    name: '',
    description: '',
    category: 'personal',
    sections: [],
    tags: [],
    estimatedTime: 10
  });
  const [newSection, setNewSection] = useState<Partial<TemplateSection>>({
    title: '',
    prompt: '',
    placeholder: '',
    required: false
  });
  const [showSectionForm, setShowSectionForm] = useState(false);

  const handleCreateTemplate = () => {
    setIsCreating(true);
    setEditingTemplate(null);
    setFormData({
      name: '',
      description: '',
      category: 'personal',
      sections: [],
      tags: [],
      estimatedTime: 10
    });
  };

  const handleEditTemplate = (template: DiaryTemplate) => {
    setEditingTemplate(template);
    setIsCreating(false);
    setFormData({ ...template, estimatedTime: template.estimatedTime || 10 });
  };

  const handleSaveTemplate = () => {
    if (!formData.name || !formData.sections || formData.sections.length === 0) {
      alert('Please provide a name and at least one section for the template.');
      return;
    }

    const templateData: DiaryTemplate = {
      id: editingTemplate?.id || `custom-${Date.now()}`,
      name: formData.name!,
      description: formData.description || '',
      category: formData.category as TemplateCategory,
      sections: formData.sections,
      tags: formData.tags || [],
      estimatedTime: formData.estimatedTime || 10,
      isCustom: true,
      isFavorite: editingTemplate?.isFavorite || false,
      usageCount: editingTemplate?.usageCount || 0,
      createdAt: editingTemplate?.createdAt || new Date(),
      updatedAt: new Date()
    };

    if (editingTemplate) {
      updateTemplate(templateData.id, templateData);
    } else {
      addCustomTemplate(templateData);
    }

    setEditingTemplate(null);
    setIsCreating(false);
    setFormData({
      name: '',
      description: '',
      category: 'personal',
      sections: [],
      tags: [],
      estimatedTime: 10
    });
  };

  const handleDeleteTemplate = (templateId: string) => {
    if (confirm('Are you sure you want to delete this template?')) {
      deleteTemplate(templateId);
    }
  };

  const handleAddSection = () => {
    if (!newSection.title || !newSection.prompt) {
      alert('Please provide both title and prompt for the section.');
      return;
    }

    const section: TemplateSection = {
      id: `section-${Date.now()}`,
      title: newSection.title,
      prompt: newSection.prompt,
      placeholder: newSection.placeholder || '',
      required: newSection.required || false,
      order: (formData.sections?.length || 0) + 1
    };

    setFormData(prev => ({
      ...prev,
      sections: [...(prev.sections || []), section]
    }));

    setNewSection({
      title: '',
      prompt: '',
      placeholder: '',
      required: false
    });
    setShowSectionForm(false);
  };

  const handleRemoveSection = (sectionId: string) => {
    setFormData(prev => ({
      ...prev,
      sections: prev.sections?.filter(s => s.id !== sectionId) || []
    }));
  };

  const handleCancel = () => {
    setEditingTemplate(null);
    setIsCreating(false);
    setShowSectionForm(false);
    setFormData({
      name: '',
      description: '',
      category: 'personal',
      sections: [],
      tags: [],
      estimatedTime: 10
    });
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-4xl max-h-[90vh] overflow-hidden">
        <div className="flex items-center justify-between p-6 border-b">
          <h2 className="text-xl font-semibold text-gray-900">
            Template Manager
          </h2>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        <div className="p-6 overflow-y-auto max-h-[calc(90vh-120px)]">
          {!isCreating && !editingTemplate ? (
            <div>
              <div className="flex items-center justify-between mb-6">
                <h3 className="text-lg font-medium text-gray-900">
                  Custom Templates ({customTemplates.length})
                </h3>
                <button
                  onClick={handleCreateTemplate}
                  className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                >
                  <Plus className="w-4 h-4" />
                  Create Template
                </button>
              </div>

              {customTemplates.length === 0 ? (
                <div className="text-center py-12">
                  <div className="text-gray-400 mb-4">
                    <Plus className="w-12 h-12 mx-auto" />
                  </div>
                  <h3 className="text-lg font-medium text-gray-900 mb-2">
                    No Custom Templates
                  </h3>
                  <p className="text-gray-600 mb-4">
                    Create your first custom template to get started.
                  </p>
                  <button
                    onClick={handleCreateTemplate}
                    className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                  >
                    Create Template
                  </button>
                </div>
              ) : (
                <div className="grid gap-4">
                  {customTemplates.map((template) => (
                    <div key={template.id} className="border rounded-lg p-4 hover:shadow-md transition-shadow">
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <h4 className="font-medium text-gray-900 mb-1">
                            {template.name}
                          </h4>
                          <p className="text-sm text-gray-600 mb-2">
                            {template.description}
                          </p>
                          <div className="flex items-center gap-4 text-sm text-gray-500">
                            <span className="capitalize">
                              {TEMPLATE_CATEGORIES[template.category]}
                            </span>
                            <span>{template.sections.length} sections</span>
                            <span>{template.estimatedTime} min</span>
                            <span>Used {template.usageCount} times</span>
                          </div>
                        </div>
                        <div className="flex items-center gap-2 ml-4">
                          <button
                            onClick={() => handleEditTemplate(template)}
                            className="p-2 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                            title="Edit template"
                          >
                            <Edit2 className="w-4 h-4" />
                          </button>
                          <button
                            onClick={() => handleDeleteTemplate(template.id)}
                            className="p-2 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                            title="Delete template"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          ) : (
            <div>
              <div className="flex items-center justify-between mb-6">
                <h3 className="text-lg font-medium text-gray-900">
                  {isCreating ? 'Create New Template' : 'Edit Template'}
                </h3>
                <div className="flex items-center gap-2">
                  <button
                    onClick={handleSaveTemplate}
                    className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
                  >
                    <Save className="w-4 h-4" />
                    Save
                  </button>
                  <button
                    onClick={handleCancel}
                    className="flex items-center gap-2 px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
                  >
                    <X className="w-4 h-4" />
                    Cancel
                  </button>
                </div>
              </div>

              <div className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Template Name *
                    </label>
                    <input
                      type="text"
                      value={formData.name || ''}
                      onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      placeholder="Enter template name"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Category
                    </label>
                    <select
                      value={formData.category || 'personal'}
                      onChange={(e) => setFormData(prev => ({ ...prev, category: e.target.value as TemplateCategory }))}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    >
                      {Object.entries(TEMPLATE_CATEGORIES).map(([key, label]) => (
                        <option key={key} value={key}>{String(label)}</option>
                      ))}
                    </select>
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Description
                  </label>
                  <textarea
                    value={formData.description || ''}
                    onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    rows={3}
                    placeholder="Describe what this template is for"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Estimated Time (minutes)
                  </label>
                  <input
                    type="number"
                    value={formData.estimatedTime || 10}
                    onChange={(e) => setFormData(prev => ({ ...prev, estimatedTime: parseInt(e.target.value) || 10 }))}
                    className="w-32 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    min="1"
                    max="120"
                  />
                </div>

                <div>
                  <div className="flex items-center justify-between mb-4">
                    <h4 className="text-md font-medium text-gray-900">
                      Template Sections ({formData.sections?.length || 0})
                    </h4>
                    <button
                      onClick={() => setShowSectionForm(true)}
                      className="flex items-center gap-2 px-3 py-1 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm"
                    >
                      <Plus className="w-4 h-4" />
                      Add Section
                    </button>
                  </div>

                  {showSectionForm && (
                    <div className="border rounded-lg p-4 mb-4 bg-gray-50">
                      <h5 className="font-medium text-gray-900 mb-3">Add New Section</h5>
                      <div className="space-y-3">
                        <div>
                          <label className="block text-sm font-medium text-gray-700 mb-1">
                            Section Title *
                          </label>
                          <input
                            type="text"
                            value={newSection.title || ''}
                            onChange={(e) => setNewSection(prev => ({ ...prev, title: e.target.value }))}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                            placeholder="e.g., Today's Highlights"
                          />
                        </div>
                        <div>
                          <label className="block text-sm font-medium text-gray-700 mb-1">
                            Prompt *
                          </label>
                          <textarea
                            value={newSection.prompt || ''}
                            onChange={(e) => setNewSection(prev => ({ ...prev, prompt: e.target.value }))}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                            rows={2}
                            placeholder="What question or instruction should guide this section?"
                          />
                        </div>
                        <div>
                          <label className="block text-sm font-medium text-gray-700 mb-1">
                            Placeholder Text
                          </label>
                          <input
                            type="text"
                            value={newSection.placeholder || ''}
                            onChange={(e) => setNewSection(prev => ({ ...prev, placeholder: e.target.value }))}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                            placeholder="Hint text for users"
                          />
                        </div>
                        <div className="flex items-center">
                          <input
                            type="checkbox"
                            id="required"
                            checked={newSection.required || false}
                            onChange={(e) => setNewSection(prev => ({ ...prev, required: e.target.checked }))}
                            className="mr-2"
                          />
                          <label htmlFor="required" className="text-sm text-gray-700">
                            Required section
                          </label>
                        </div>
                        <div className="flex items-center gap-2">
                          <button
                            onClick={handleAddSection}
                            className="px-3 py-1 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors text-sm"
                          >
                            Add Section
                          </button>
                          <button
                            onClick={() => {
                              setShowSectionForm(false);
                              setNewSection({ title: '', prompt: '', placeholder: '', required: false });
                            }}
                            className="px-3 py-1 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors text-sm"
                          >
                            Cancel
                          </button>
                        </div>
                      </div>
                    </div>
                  )}

                  {formData.sections && formData.sections.length > 0 ? (
                    <div className="space-y-3">
                      {formData.sections.map((section, index) => (
                        <div key={section.id} className="border rounded-lg p-3 bg-white">
                          <div className="flex items-start justify-between">
                            <div className="flex-1">
                              <div className="flex items-center gap-2 mb-1">
                                <span className="text-sm font-medium text-gray-900">
                                  {index + 1}. {section.title}
                                </span>
                                {section.required && (
                                  <span className="text-xs bg-red-100 text-red-800 px-2 py-0.5 rounded">
                                    Required
                                  </span>
                                )}
                              </div>
                              <p className="text-sm text-gray-600 mb-1">{section.prompt}</p>
                              {section.placeholder && (
                                <p className="text-xs text-gray-500 italic">
                                  Placeholder: {section.placeholder}
                                </p>
                              )}
                            </div>
                            <button
                              onClick={() => handleRemoveSection(section.id)}
                              className="p-1 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded transition-colors"
                              title="Remove section"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          </div>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <div className="text-center py-8 text-gray-500">
                      <p>No sections added yet. Click "Add Section" to get started.</p>
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default TemplateManager;